﻿#region 程序集引用
using System;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
#endregion
namespace Tools
{
    /// <summary>
    /// 字符串常用方法
    /// </summary>
    public static class OpString
    {
        #region 字符数组至字符串的转换
        // 字符数组返回字符串
        /// <summary>
        /// 传入字符数组返回字符串
        /// </summary>
        /// <param name="chrarr">字符串数组</param>
        /// <returns>返回字符数组的字符串值</returns>
        public static string GetString(char[] chrarr)
        {
            string result = string.Empty;

            for (int i = 0; i < chrarr.Length; i++)
            {
                result += chrarr[i];
            }

            return result;
        }
        #endregion

        #region 字符串长度截取
        /// <summary>
        /// 截取字符串的指定长度
        /// </summary>
        /// <param name="_str">目标字符串</param>
        /// <param name="_length">要截取的长度</param>
        /// <param name="_dot">是否显示  『...』 </param>
        /// <returns>返回截取的子字符串</returns>
        public static string IterceptString(string _str, int _length, bool _dot)
        {
            if (string.IsNullOrEmpty(_str)) return _str;

            int length = _length;
            int j = 0;

            for (int i = 0; i < _str.Length; i++)
            {
                if (j >= _length)
                {
                    if (_dot)
                    {
                        return _str.Substring(0, length) + "...";
                    }
                    else
                    {
                        return _str.Substring(0, length);
                    }
                }
                if ((int)(_str[i]) > 127)
                {
                    length--;
                    j += 2;
                }
                else
                    j++;
            }

            return _str;
        }
        #endregion

        #region 获得随机数字字母的混合字符串
        /// <summary>
        /// 获得随机数字字母的混合字符串
        /// </summary>
        /// <param name="_length">要获取的字符串长度</param>
        /// <returns>随机字符串</returns>
        public static string GetRamdomLetterNumString(int _length)
        {
            char[] chr = { 'a', 'y', 's', 'V', 'b', 'c', 'd', 'f', 'D', 'g', 'h', 'w', 'F', '3', 'G', 'j', '2', 'x', 'S', 'k', '4', 'H', 'L', 'z', '6', 'q', 'J', '5', 'Q', 'T', 'W', 'K', 'A', 'e', '7', 'E', 'r', 't', 'Y', 'P', 'n', 'p', '8', 'm', '9', 'R', 'Z', 'X', 'C', 'v', 'B', 'N', 'M' };
            char[] result = new char[_length];
            Random rnd = new Random();
            int seed = rnd.Next(int.Parse(DateTime.Now.ToString("ssffffff")));

            for (int i = 0; i < _length; i++)
            {
                int chrIndex = new Random(seed * (i + 1)).Next(1, chr.Length - 1);
                result[i] = chr[chrIndex];
            }
            return GetString(result);
        }
        #endregion

        #region 获得随机数字字符串
        /// <summary>
        /// 获得随机数字字符串
        /// </summary>
        /// <param name="_length">要获取的字符串长度</param>
        /// <returns>随机字符串</returns>
        public static string GetRandomNumString(int _length)
        {
            string result = "";
            Random rnd = new Random();
            int seed = rnd.Next(int.Parse(DateTime.Now.ToString("ssffffff")));

            for (int i = 0; i < _length; i++)
            {
                int temp = new Random(seed * (i + 1)).Next(1, 10);
                result += temp.ToString();
            }
            return result;
        }
        #endregion

        #region 获得随机字母字符串
        /// <summary>
        /// 获得随机字母字符串
        /// </summary>
        /// <param name="_length">要获取的字符串长度</param>
        /// <returns>随机字符串</returns>
        public static string GetRandomLetterString(int _length)
        {
            char[] chr = { 'a', 'Z', 'B', 'd', 'G', 'h', 'k', 'M', 'N', 'q', 'w', 'U', 'b', 'W', 'c', 'L', 'S', 'x', 'y', 'e', 'F', 'E', 'j', 'X', 'A', 'C', 'f', 'H', 'D', 'g', 'I', 'J', 'i', 'K', 'p', 'Q', 'P', 'r', 's', 't', 'u', 'v', 'Y', 'z', 'V' };
            char[] result = new char[_length];
            Random rnd = new Random();

            for (int i = 0; i < _length; i++)
            {
                result[i] += chr[rnd.Next(10) + rnd.Next(20) + rnd.Next(14)];
            }

            return GetString(result);
        }
        #endregion

        #region 随机生成汉字
        /// <summary>
        /// 随机生成汉字字符串
        /// </summary>
        /// <param name="_length">汉字个数</param>
        /// <returns>返回汉字字符串</returns>
        public static string GetRandomCharacter(int _length)
        {
            string result = string.Empty;
            Random rnd = new Random();
            System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("GB2312");

            for (int i = 0; i < _length; i++)
            {
                byte[] bytes = new byte[2];
                bytes[0] = Convert.ToByte(rnd.Next(176, 215));//汉字常用字从16(B0)区开始到55(D7)区
                bytes[1] = Convert.ToByte(rnd.Next(161, 254));//每区94个汉字从（01）A1开始
                result += encoder.GetString(bytes);
            }

            return result;
        }
        #endregion

        #region 获取随机文件名
        /// <summary>
        /// 获取随机文件名（日期加随机字符）
        /// </summary>
        /// <param name="_charNum">除日期外的随机字符个数</param>
        /// <returns>随机文件名</returns>
        public static string GetRandomFileName(int _charNum)
        {
            string result = DateTime.Now.ToString("yyyyMMddhhmmss");
            char[] chr = { 'a', 'y', '0', 's', '1', 'V', 'b', 'I', 'c', 'd', 'f', 'D', 'g', 'h', 'w', 'F', '3', 'G', 'j', '2', 'x', 'S', 'k', '4', 'H', 'L', 'z', '6', 'q', 'J', '5', 'Q', 'T', 'W', 'K', 'A', 'e', '7', 'E', 'r', 't', 'Y', 'P', 'n', 'i', 'p', '8', 'm', '9', 'R', 'Z', 'X', 'C', 'v', 'B', 'N', 'M' };
            char[] temp = new char[_charNum];
            Random rnd = new Random();
            for (int i = 0; i < _charNum; i++)
            {
                int random = rnd.Next(rnd.Next(23)) + rnd.Next(rnd.Next(26)) + rnd.Next(rnd.Next(7));
                temp[i] = chr[random];
            }
            result += GetString(temp);
            return result;
        }
        #endregion

        /// <summary> 
        /// 在指定的字符串列表CnStr中检索符合拼音索引字符串 
        /// </summary> 
        /// <param name="CnStr">汉字字符串</param> 
        /// <returns>相对应的汉语拼音首字母串</returns> 
        public static string GetSpellCode(string CnStr)
        {
            string strTemp = "";
            int iLen = CnStr.Length;
            int i = 0;

            for (i = 0; i <= iLen - 1; i++)
            {
                strTemp += GetCharSpellCode(CnStr.Substring(i, 1));
            }

            return strTemp;
        }

        /// <summary> 
        /// 得到一个汉字的拼音第一个字母，如果是一个英文字母则直接返回大写字母 
        /// </summary>

        /// <param name="CnChar">单个汉字</param>

        /// <returns>单个大写字母</returns>

        private static string GetCharSpellCode(string CnChar)
        {

            long iCnChar;

            byte[] ZW = System.Text.Encoding.Default.GetBytes(CnChar);

            //如果是字母，则直接返回首字母

            if (ZW.Length == 1)
            {
                return CutString(CnChar.ToUpper(), 1);
            }
            else
            {
                // get the array of byte from the single char
                int i1 = (short)(ZW[0]);
                int i2 = (short)(ZW[1]);
                iCnChar = i1 * 256 + i2;
            }

            // iCnChar match the constant
            if ((iCnChar >= 45217) && (iCnChar <= 45252))
            {
                return "A";
            }
            else if ((iCnChar >= 45253) && (iCnChar <= 45760))
            {
                return "B";
            }
            else if ((iCnChar >= 45761) && (iCnChar <= 46317))
            {
                return "C";
            }
            else if ((iCnChar >= 46318) && (iCnChar <= 46825))
            {
                return "D";
            }
            else if ((iCnChar >= 46826) && (iCnChar <= 47009))
            {
                return "E";
            }
            else if ((iCnChar >= 47010) && (iCnChar <= 47296))
            {
                return "F";
            }
            else if ((iCnChar >= 47297) && (iCnChar <= 47613))
            {
                return "G";
            }
            else if ((iCnChar >= 47614) && (iCnChar <= 48118))
            {
                return "H";
            }
            else if ((iCnChar >= 48119) && (iCnChar <= 49061))
            {
                return "J";
            }
            else if ((iCnChar >= 49062) && (iCnChar <= 49323))
            {
                return "K";
            }
            else if ((iCnChar >= 49324) && (iCnChar <= 49895))
            {
                return "L";
            }
            else if ((iCnChar >= 49896) && (iCnChar <= 50370))
            {
                return "M";
            }
            else if ((iCnChar >= 50371) && (iCnChar <= 50613))
            {
                return "N";
            }
            else if ((iCnChar >= 50614) && (iCnChar <= 50621))
            {
                return "O";
            }
            else if ((iCnChar >= 50622) && (iCnChar <= 50905))
            {
                return "P";
            }
            else if ((iCnChar >= 50906) && (iCnChar <= 51386))
            {
                return "Q";
            }
            else if ((iCnChar >= 51387) && (iCnChar <= 51445))
            {
                return "R";
            }
            else if ((iCnChar >= 51446) && (iCnChar <= 52217))
            {
                return "S";
            }
            else if ((iCnChar >= 52218) && (iCnChar <= 52697))
            {
                return "T";
            }
            else if ((iCnChar >= 52698) && (iCnChar <= 52979))
            {
                return "W";
            }
            else if ((iCnChar >= 52980) && (iCnChar <= 53640))
            {
                return "X";
            }
            else if ((iCnChar >= 53689) && (iCnChar <= 54480))
            {
                return "Y";
            }
            else if ((iCnChar >= 54481) && (iCnChar <= 55289))
            {
                return "Z";
            }
            else
                return ("?");
        }

        /// <summary>
        /// 截取字符串长度（可选是否追加省略号）
        /// </summary>
        /// <param name="str">被截取的字符串</param>
        /// <param name="len">目标长度（英文为1，中文为2）</param>
        /// <param name="appendEllipsis">是否追加 "..."</param>
        /// <returns>截取后的子字符串</returns>
        public static string CutString(string str, int maxLength, bool appendEllipsis = true)
        {
            if (string.IsNullOrEmpty(str) || maxLength <= 0)
                return string.Empty;

            int currentLength = 0;
            int cutIndex = 0;

            while (cutIndex < str.Length && currentLength < maxLength)
            {
                char c = str[cutIndex];
                int charLength = c > 127 ? 2 : 1;

                if (currentLength + charLength > maxLength)
                    break;

                currentLength += charLength;
                cutIndex++;
            }

            if (cutIndex < str.Length)
                return str.Substring(0, cutIndex) + (appendEllipsis ? "..." : "");
            else
                return str;
        }



        /// <summary>
        /// 验证是否是正整数
        /// </summary>
        /// <param name="str">字符串内容</param>
        /// <returns></returns>
        public static bool IsNumber(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return false;
            return Regex.IsMatch(str.Trim(), @"^\d+$");
        }


        /// <summary>
        /// 验证是否是整数
        /// </summary>
        /// <param name="str">字符串内容</param>
        /// <returns></returns>
        public static bool IsInt(string str)
        {
            return int.TryParse(str, out _);
        }


        /// <summary>
        /// 验证是否是数字
        /// </summary>
        /// <param name="str">字符串内容</param>
        /// <returns></returns>
        public static bool IsNumeric(string str)
        {
            return double.TryParse(str, out _);
        }

        /// <summary>
        /// 验证是否为日期
        /// </summary>
        /// <param name="str">日期内容</param>
        /// <returns></returns>
        public static bool IsDate(string str)
        {
            bool isTrue;

            try
            {
                if (!string.IsNullOrEmpty(str) && str.Trim() != "")
                {
                    DateTime.Parse(str);
                    isTrue = true;
                }
                else
                {
                    isTrue = false;
                }
            }
            catch
            {
                isTrue = false;
            }

            return isTrue;
        }

        /// <summary>
        /// 格式化价格
        /// </summary>
        /// <param name="pric"></param>
        /// <returns></returns>
        public static float ForamtPrice(float pric)
        {
            return float.Parse(string.Format("{0:00}", pric));
        }
        /// <summary>
        /// 格式化价格
        /// </summary>
        /// <param name="pric"></param>
        /// <returns></returns>
        public static string ForamtPriceShow(float pric)
        {
            return string.Format("{0:0.00}", pric);
        }

        /// <summary>
        /// /html标签转化成text
        /// </summary>
        /// <param name="htmlStr"></param>
        /// <param name="removeSpace">移除空格</param>
        /// <returns></returns>
        public static string Html2Text(string htmlStr, bool removeSpace = true)
        {
            if (String.IsNullOrEmpty(htmlStr))
            {
                return "";
            }
            string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 
            string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 
            string regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式 
            htmlStr = Regex.Replace(htmlStr, regEx_style, "");//删除css
            htmlStr = Regex.Replace(htmlStr, regEx_script, "");//删除js
            htmlStr = Regex.Replace(htmlStr, regEx_html, "");//删除html标记
            if (removeSpace)
            {
                htmlStr = Regex.Replace(htmlStr, "\\s*|\t|\r|\n", "");//去除tab、空格、空行
                htmlStr = htmlStr.Replace(" ", "");
            }
            htmlStr = htmlStr.Replace("\"", "");//去除异常的引号" " "
            htmlStr = htmlStr.Replace("\"", "");
            return htmlStr.Trim();
        }

        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="strHtml">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        public static string ScriptHTML(string strHtml)
        {
            string[] aryReg = { @"<script[^>]*?>.*?</script>", @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>", @"([\r\n])[\s]+", @"&(quot|#34);", @"&(amp|#38);", @"&(lt|#60);", @"&(gt|#62);", @"&(nbsp|#160);", @"&(iexcl|#161);", @"&(cent|#162);", @"&(pound|#163);", @"&(copy|#169);", @"&#(\d+);", @"-->", @"<!--.*\n" };
            string[] aryRep = { "", "", "", "\"", "&", "<", ">", " ", "\xa1", "\xa2", "\xa3", "\xa9", "", "\r\n", "" };
            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }
            strOutput?.Replace("<", "");
            strOutput?.Replace(">", "");
            strOutput?.Replace("\r\n", "");
            return strOutput;
        }

        /// <summary>
        /// 将字符串中的中文删除
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string FilterChineseLetter(string c)
        {
            string result = "";

            for (int i = 0; i < c.Length; i++)
            {
                var arrByte = System.Text.Encoding.GetEncoding("gb2312").GetBytes(c.Substring(i, 1));

                if (arrByte.Length == 1)
                {
                    result += c.Substring(i, 1);
                }
            }
            return result;
        }
    }
}

